import { useEffect, useMemo, useState, useRef } from "react";
import { Checkbox, Form, Space, Tag, Popup, Divider, Input, TextArea, Picker, Radio, Cascader, Toast } from "antd-mobile";
import { DownOutline, AddOutline, CloseOutline, UploadOutline, TextOutline, CloseCircleOutline } from 'antd-mobile-icons';
import dayjs from "dayjs";
import { useNavigate, useSearchParams } from "react-router-dom";
import Styles from "./index.module.less";
import store from '@/reducer/store'
import CalendarPopup from '@/components/CalendarPopup'
import country from '@/assets/ts/country'
import { randomRangeId } from "@/utils/commonUtils"
import { getHandleInfo, uploadFile, negotiationAdd } from '@/service/projectDetail'


const Index: React.FC<any> = () => {
    const [search] = useSearchParams();
    const searchId = search?.get('id')
    const infoId = search?.get('infoId')
    const navigate = useNavigate();
    const [countryValue, setCountryValue] = useState([]);
    const [countryVis, setCountryVis] = useState(false);
    const [uploadFileList, setUploadFileList] = useState<any>([]);
    const upLoadRef = useRef<any>(null);
    const [params, setParams] = useState<any>({
        jointType: 2,
        jointDate: '',
        jointItem: '',
        governmentContacts: '',
        governmentContactsPhone: '',
        jointContacts: '',
        jointContactsPhone: '',
        jointContactsPost: '',
        isJointLeader: '',
        isSecretProject: '',
        nextStep: '',
        registerType: '',
        settledType: '',
        spaceSize: '',
        creditCode: '',
        stopReason: '',
        jointStatus: '',
        isOut: 0,
        supportProveAnnexName: null,
        supportProveAnnexUrl: null
    });
    const changeParams = (val: any, key: string) => {
        setParams((value: any) => {
            value[key] = val
            return { ...value }
        })
    }
    const [CalendarPopupVis, setCalendarPopupVis] = useState(false)
    const [CalendarTime, setCalendarTime] = useState('')
    const showPopup = (status: any) => {
        setCalendarPopupVis(status)
    }
    const enterDate = (e: any) => {
        let date: any = dayjs(e).format('YYYY-MM-DD')
        setCalendarTime(date)
    }
    const changeNext = (e: any) => {
        setParams((value: any) => {
            value.nextStep = e
            value.jointStatus = []
            return { ...value }
        })
    }
    //市领导
    let [cityLeaders, setCityLeaders] = useState({
        add: true,
        tags: [],
        value: '',
    })
    //区领导
    let [districtLeaders, setDistrictLeaders] = useState({
        add: true,
        tags: [],
        value: '',
    })
    //局领导
    let [bureauLeaders, setBureauLeaders] = useState({
        add: true,
        tags: [],
        value: '',
    })
    const blurLeaders = (key: any) => {
        let funcObj = {
            city: setCityLeaders,
            district: setDistrictLeaders,
            bureau: setBureauLeaders
        }
        funcObj[key]((params: any) => {
            if (params.value && params.tags.indexOf(params.value) == -1) {
                params.tags.push(params.value)
            }
            params.add = true
            params.value = ""
            return { ...params }
        })
    }
    const deleteLeaders = (item: any, key: any) => {
        let funcObj = {
            city: setCityLeaders,
            district: setDistrictLeaders,
            bureau: setBureauLeaders
        }
        funcObj[key]((params: any) => {
            for (let i = params.tags.length - 1; i >= 0; i--) {
                if (params.tags[i] == item) {
                    params.tags.splice(i, 1)
                }
            }
            return { ...params }
        })
    }
    const showTagsInput = (key: any) => {
        let funcObj = {
            city: setCityLeaders,
            district: setDistrictLeaders,
            bureau: setBureauLeaders
        }
        funcObj[key]((params: any) => {
            params.add = false
            return { ...params }
        })
    }
    const changeTagInput = (val: any, key: any) => {
        let funcObj = {
            city: setCityLeaders,
            district: setDistrictLeaders,
            bureau: setBureauLeaders
        }
        funcObj[key]((params: any) => {
            params.value = val
            return { ...params }
        })
    }

    const getHandleInfoData = async () => {
        const res: any = await getHandleInfo(infoId)
        const { code, data } = res?.data
        if (code == 0) {
            let {
                jointDate,
                jointItem,
                governmentContacts,
                governmentContactsPhone,
                jointContacts,
                jointContactsPhone,
                jointContactsPost,
                isJointLeader,
                isSecretProject,
                nextStep,
                registerType,
                settledType,
                spaceSize,
                creditCode,
                stopReason,
                jointLeader1,
                jointLeader2,
                jointLeader3,
                jointStatus,
                jointCity,
                isOut
            } = data;
            setParams((value: any) => {
                value.jointItem = jointItem
                value.governmentContacts = governmentContacts
                value.governmentContactsPhone = governmentContactsPhone
                value.jointContacts = jointContacts
                value.jointContactsPhone = jointContactsPhone
                value.jointContactsPost = jointContactsPost
                value.isJointLeader = isJointLeader || 0
                value.isSecretProject = isSecretProject || 0
                value.isOut = isOut || 0
                value.nextStep = nextStep
                value.registerType = registerType || 2
                value.settledType = settledType || 1
                value.spaceSize = spaceSize || ''
                value.creditCode = creditCode || ''
                value.stopReason = stopReason || ''
                value.jointStatus = jointStatus?.split(',') || ''
                return { ...value }
            })
            setCountryValue(isOut == 1 ? jointCity?.split(',') : [])
            jointLeader1 && setCityLeaders((value: any) => {
                value.tags = jointLeader1.split(',')
                return { ...value }
            })
            jointLeader2 && setDistrictLeaders((value: any) => {
                value.tags = jointLeader2.split(',')
                return { ...value }
            })
            jointLeader3 && setBureauLeaders((value: any) => {
                value.tags = jointLeader3.split(',')
                return { ...value }
            })
            jointDate && setCalendarTime(jointDate)
        }
    }

    const cancel = () => {
        navigate(-1)
    }

    // 处理上传参数
    const getUploadData = (value: any) => {
        let supportProveAnnexUrl: any = "";
        let supportProveAnnexName: any = "";
        if (value?.length > 0) {
          value?.forEach((item: any) => {
            supportProveAnnexUrl =
              supportProveAnnexUrl +
              `${supportProveAnnexUrl && ","}${item.url}`;
            supportProveAnnexName =
              supportProveAnnexName + `${supportProveAnnexName && ","}${item.name}`;
          });
        }
        return [supportProveAnnexUrl ?? null, supportProveAnnexName ?? null];
      };

    const submit = async () => {
        const verify = [
            [CalendarTime === '', '请选择对接时间'],
            [params.jointItem === '', '对接事项不能为空'],
            [params.jointStatus === '', '对接状态不能为空'],
            [params.governmentContacts === '', '政府对接人不能为空'],
            [params.governmentContactsPhone === '', '政府对接人手机不能为空'],
            [params.jointContacts === '', '企业联系人不能为空'],
            [params.jointContactsPhone === '', '企业联系人手机不能为空'],
            [params.jointContactsPost === '', '企业联系人职务不能为空'],
            [params.isJointLeader === '', '请选择是否洽谈对接领导'],
            [params.isJointLeader == 1 && cityLeaders.tags.length === 0 && districtLeaders.tags.length === 0 && bureauLeaders.tags.length === 0, '请添加对接领导人'],
            [params.isSecretProject === '', '请选择是否保密项目'],
            [params.nextStep === '', '请选择下一步安排'],
            [params.nextStep === 2 && uploadFileList?.length == 0, '请上传项目计划书'],
            [params.isOut === 1 && countryValue?.length == 0, '请选择对接城市'],
            [params.nextStep == 3 && params.stopReason === '', '终止原因不能为空'],
        ]
        for (let i = 0; i < verify.length; i++) {
            if (verify[i][0]) {
                return Toast.show({ content: verify[i][1] })
            }
        }
        if (params?.isOut) {
            params.jointCity = countryValue.join(",");
        } else {
            params.jointCity = null;
        }
        let query: any = {
            ...params,
            ...(infoId && { id: infoId }),
            investPurposeInfoId: searchId,
            supportProveAnnexUrl: getUploadData(uploadFileList)?.[0],
            supportProveAnnexName: getUploadData(uploadFileList)?.[1],
            jointStatus: params?.jointStatus?.toString(),
            jointDate: CalendarTime,
            ...(params.isJointLeader == 1 && {
                jointLeader1: cityLeaders.tags.toString(),
                jointLeader2: districtLeaders.tags.toString(),
                jointLeader3: bureauLeaders.tags.toString(),
            }),
        }

        let res: any = await negotiationAdd(query)
        const { code, msg } = res?.data
        if (code == 0) {
            navigate(-1)
            // navigate(`/project-detail?id=${searchId}`);
        }
        Toast.show({ content: msg })
    }
    useEffect(() => {
        infoId && getHandleInfoData()
    }, [])

    const dockingStatus1: any = [
        { name: '接触非实控人', id: '1' },
        { name: '接触实控人', id: '2' },
        { name: '线上对接', id: '3' },
        { name: '线下拜访', id: '4' },
        { name: '实地看房/考察', id: '5' },
    ]

    const dockingStatus2: any = [
        { name: '接触非实控人', id: '1' },
        { name: '接触实控人', id: '2' },
        { name: '组建项目专班', id: '6' },
        { name: '形成落户方案', id: '7' },
        { name: '政策匹配', id: '8' },
        { name: '选定办公地址', id: '9' },
        { name: '签署合作协议/合作备忘录', id: '10' },
    ]


    const enterCountry = (value: any) => {
        setCountryValue(value);
        setCountryVis(false)
    }

    const inputUploadFile = (e: any) => {
        let fileReader = new FileReader();
        let id = randomRangeId(9)
        fileReader.onload = function () {
            const getUploadData = async () => {
                let formData = new FormData();
                formData.append("file", e.target.files[0]);
                let res: any = await uploadFile(formData)
                let { data } = res
                if (/^(http|https):\/\//.test(data)) {
                    setUploadFileList((list: any) => {
                        list.push({ name: e.target.files[0].name, url: data, id })
                        upLoadRef.current.value = '';
                        return [...list]
                    })
                } else {
                    upLoadRef.current.value = '';
                    return Toast.show({ content: "上传失败" })
                }
            }
            getUploadData()
        }
        // base64方式读取
        fileReader.readAsDataURL(e.target.files[0]);
    };

    // 移除上传文件
    const handleRemoveFile = (index: number) => {
        const dataList = uploadFileList;
        dataList.splice(index, 1);
        setUploadFileList([...dataList]);
        return;
      };


    const dockConfig: any = { 1: dockingStatus1, 2: dockingStatus2, 3: dockingStatus1 }

    return (<>
        <div className={Styles.Baseinfo}>
            <div className={Styles.blockItem}>
                <div className={Styles.BaseinfoTitle}>初步对接记录</div>
                <div className={Styles.BaseinfoBlock}>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>对接时间：</div>
                        <div className={Styles.BaseinfoInput} onClick={() => { showPopup(true) }}>
                            <div className={Styles.BaseinfoText}>{CalendarTime || '请选择'}</div>
                            <CalendarPopup vis={CalendarPopupVis} showPopup={showPopup} enterDate={enterDate} />
                        </div>
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>是否走出去：</div>
                        <div className={Styles.BaseinfoInput}>
                            <Radio.Group value={params.isOut} onChange={(e) => {
                                setParams((value: any) => {
                                    value.isOut = e
                                    return { ...value }
                                })
                            }}>
                                <div className={Styles.CheckboxItem}>
                                    <Radio value={0}></Radio>否
                                </div>
                                <div className={Styles.CheckboxItem}>
                                    <Radio value={1}></Radio>是
                                </div>
                            </Radio.Group>
                        </div>
                        {params?.isOut == 1 && <div className={Styles.city_content} onClick={() => { setCountryVis(true) }}>
                            <div className={Styles.BaseinfoText}>{countryValue.join('/') || '请选择对接城市'}</div>
                            <DownOutline />
                            <Cascader
                                options={country}
                                value={countryValue}
                                visible={countryVis}
                                onCancel={() => { setCountryVis(false) }}
                                onConfirm={(value) => {
                                    enterCountry(value)
                                }} />
                        </div>}
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>对接状态：</div>
                        <div className={Styles.BaseinfoStatus}>
                            <Checkbox.Group value={params?.jointStatus} onChange={val => {
                                changeParams(val, 'jointStatus')
                            }}>
                                {dockConfig?.[params?.nextStep || 1].map((item: any) => (
                                    <Checkbox value={item.id} key={item.id}>
                                        {item.name}
                                    </Checkbox>
                                ))}
                            </Checkbox.Group>
                        </div>
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>对接事项：</div>
                        <div className={Styles.BaseinfoInput}>
                            <TextArea
                                placeholder='请输入'
                                value={params.jointItem}
                                onChange={val => {
                                    changeParams(val, 'jointItem')
                                }}
                            />
                        </div>
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>政府对接人：</div>
                        <div className={Styles.BaseinfoInput}>
                            <Input
                                placeholder='请输入'
                                value={params.governmentContacts}
                                onChange={val => {
                                    changeParams(val, 'governmentContacts')
                                }}
                            />
                        </div>
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>政府对接人手机：</div>
                        <div className={Styles.BaseinfoInput}>
                            <Input
                                placeholder='请输入'
                                value={params.governmentContactsPhone}
                                onChange={val => {
                                    changeParams(val, 'governmentContactsPhone')
                                }}
                            />
                        </div>
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>企业联系人：</div>
                        <div className={Styles.BaseinfoInput}>
                            <Input
                                placeholder='请输入'
                                value={params.jointContacts}
                                onChange={val => {
                                    changeParams(val, 'jointContacts')
                                }}
                            />
                        </div>
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>企业联系人手机：</div>
                        <div className={Styles.BaseinfoInput}>
                            <Input
                                placeholder='请输入'
                                value={params.jointContactsPhone}
                                onChange={val => {
                                    changeParams(val, 'jointContactsPhone')
                                }}
                            />
                        </div>
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>企业联系人职务：</div>
                        <div className={Styles.BaseinfoInput}>
                            <Input
                                placeholder='请输入'
                                value={params.jointContactsPost}
                                onChange={val => {
                                    changeParams(val, 'jointContactsPost')
                                }}
                            />
                        </div>
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>是否洽谈对接领导：</div>
                        <div className={Styles.BaseinfoInput}>
                            <Radio.Group value={params.isJointLeader} onChange={(e) => {
                                setParams((value: any) => {
                                    value.isJointLeader = e
                                    return { ...value }
                                })
                            }}>
                                <div className={Styles.CheckboxItem}>
                                    <Radio value={0}></Radio>未对接
                                </div>
                                <div className={Styles.CheckboxItem}>
                                    <Radio value={1}></Radio>已对接
                                </div>
                            </Radio.Group>
                        </div>
                    </div>
                    {params.isJointLeader == 1 && <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>对接人领导(类型及姓名)：</div>
                        <div className={Styles.BaseinfoInput}>
                            <div className={Styles.leaderLabel}>市领导</div>
                            <div className={Styles.tags}>
                                {cityLeaders.tags.map((item: any, index: any) => {
                                    return <div className={Styles.tagsItem} onClick={() => deleteLeaders(item, 'city')} key={index}>{item}<CloseOutline /></div>
                                })}
                                {cityLeaders.add && <div className={Styles.tagsAdd} onClick={() => { showTagsInput('city') }}><AddOutline />添加</div>}
                                {!cityLeaders.add && <Input
                                    className={Styles.tagsInput}
                                    placeholder='请输入'
                                    value={cityLeaders.value}
                                    onBlur={() => blurLeaders('city')}
                                    onChange={val => { changeTagInput(val, 'city') }}
                                />}
                            </div>
                        </div>
                        <div className={Styles.BaseinfoInput}>
                            <div className={Styles.leaderLabel}>区领导</div>
                            <div className={Styles.tags}>
                                {districtLeaders.tags.map((item: any, index: any) => {
                                    return <div className={Styles.tagsItem} onClick={() => deleteLeaders(item, 'district')} key={index}>{item}<CloseOutline /></div>
                                })}
                                {districtLeaders.add && <div className={Styles.tagsAdd} onClick={() => { showTagsInput('district') }}><AddOutline />添加</div>}
                                {!districtLeaders.add && <Input
                                    className={Styles.tagsInput}
                                    placeholder='请输入'
                                    value={districtLeaders.value}
                                    onBlur={() => blurLeaders('district')}
                                    onChange={val => { changeTagInput(val, 'district') }}
                                />}
                            </div>
                        </div>
                        <div className={Styles.BaseinfoInput}>
                            <div className={Styles.leaderLabel}>局领导</div>
                            <div className={Styles.tags}>
                                {bureauLeaders.tags.map((item: any, index: any) => {
                                    return <div className={Styles.tagsItem} onClick={() => deleteLeaders(item, 'bureau')} key={index}>{item}<CloseOutline /></div>
                                })}
                                {bureauLeaders.add && <div className={Styles.tagsAdd} onClick={() => { showTagsInput('bureau') }}><AddOutline />添加</div>}
                                {!bureauLeaders.add && <Input
                                    className={Styles.tagsInput}
                                    placeholder='请输入'
                                    value={bureauLeaders.value}
                                    onBlur={() => blurLeaders('bureau')}
                                    onChange={val => { changeTagInput(val, 'bureau') }}
                                />}
                            </div>
                        </div>
                    </div>}
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>是否保密项目：</div>
                        <div className={Styles.BaseinfoInput}>
                            <Radio.Group value={params.isSecretProject} onChange={(e) => {
                                setParams((value: any) => {
                                    value.isSecretProject = e
                                    return { ...value }
                                })
                            }}>
                                <div className={Styles.CheckboxItem}>
                                    <Radio value={1}></Radio>是
                                </div>
                                <div className={Styles.CheckboxItem}>
                                    <Radio value={0}></Radio>否
                                </div>
                            </Radio.Group>
                        </div>
                    </div>
                    <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>下一步安排：</div>
                        <div className={Styles.BaseinfoInput}>
                            <Radio.Group value={params.nextStep} onChange={(e) => { changeNext(e) }}>
                                <Radio
                                    value={1}
                                    style={{
                                        "--font-size": "12px",
                                        "--gap": "6px",
                                        '--icon-size': '18px',
                                        'marginRight': '8px'
                                    }}
                                >继续对接</Radio>
                                <Radio
                                    value={2}
                                    style={{
                                        "--font-size": "12px",
                                        "--gap": "6px",
                                        '--icon-size': '18px',
                                        'marginRight': '8px'
                                    }}
                                >转为深入洽谈(拟引进)</Radio>
                                <Radio
                                    value={3}
                                    style={{
                                        "--font-size": "12px",
                                        "--gap": "6px",
                                        '--icon-size': '18px'
                                    }}
                                >终止</Radio>
                            </Radio.Group>
                        </div>
                    </div>
                    {params.nextStep == 2 && <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>项目计划书：</div>
                        <div className={Styles.uploadBlock}>
                            <div className={Styles.uploadTips}>1.请上传相关证明文件。备注：包括但不限于洽谈照片、视频会议截图、往来邮件记录、项目方名片、 盖章的其他材料（如项目计划书、投资意向表等）；或其他认定项目意向落户福田区的相关材料。</div>
                            <div className={Styles.uploadTips}>2.支持扩展名：.jpg .rar .zip .doc .docx .pdf，文件大小不超过10M</div>
                            {uploadFileList.length != 0 && uploadFileList.map((upitem: any, upindex: any) => {
                                return <div className={Styles.uploadItem} key={`file_${upindex}`}>
                                    <TextOutline />
                                    <div className={Styles.uploadItemName}>{upitem.name}</div>
                                    <CloseCircleOutline onClick={() => handleRemoveFile(upindex)} />
                                </div>
                            })}
                            <label className={Styles.uploadAdd}>
                                <input type="file" name="fileContent" ref={upLoadRef} hidden onChange={(e) => { inputUploadFile(e) }} />
                                <UploadOutline />上传文件
                            </label>
                        </div>
                    </div>}
                    {params.nextStep == 3 && <div className={Styles.BaseinfoItem}>
                        <div className={Styles.BaseinfoKey}>终止原因：</div>
                        <div className={Styles.BaseinfoInput}>
                            <TextArea
                                placeholder='请输入终止原因'
                                value={params.stopReason}
                                onChange={val => {
                                    changeParams(val, 'stopReason')
                                }}
                            />
                        </div>
                    </div>}
                </div>
            </div>
            <div className={Styles.submitBtn}>
                <div className={Styles.btnCancel} onClick={() => cancel()}>取消</div>
                <div className={Styles.btnEnter} onClick={() => submit()}>确认</div>
            </div>
        </div>
    </>)
}
export default Index;